import axios from 'taro-axios'
import config from '@/config/index'
// import { Toast } from '@nutui/nutui-taro'
import Taro from '@tarojs/taro'

// create an axios instance
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = Taro.getStorageSync('token')
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Access-Token'] = token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.errorCode === 0) {
      return res
    }
    // if the custom code is not 20000, it is judged as an error.
    switch (res.errorCode) {
      case 102: {
        Taro.showToast({
          title: res.message,
          icon: 'none',
          duration: 1000
        })
        Taro.navigateTo({ url: '/pages/login/index' })
        return Promise.reject(res || 'Error')
        // MessageBox.alert('登录超时！请重新登录', '登录超时', {
        //   confirmButtonText: '重新登录',
        //   type: 'warning',
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload();
        //   });
        // });
        // return Promise.reject(res || 'Error');
      }
      case 301: {
        Taro.showToast({
          title: res.message,
          icon: 'none',
          duration: 1000
        })
        return Promise.reject(res || 'Error')
      }
      default: {
        Taro.showToast({
          title: res.message,
          icon: 'none',
          duration: 1000
        })
        return Promise.reject(res || 'Error')
      }
    }
  },
  error => {
    console.log('err' + error) // for debug
    Taro.showToast({
      title: error.message,
      icon: 'none',
      duration: 1000
    })
    return Promise.reject(error)
  }
)

export default service
